package com.wfs.suanfa.cas;

import java.util.concurrent.atomic.AtomicInteger;

public class CasABADemo {
    public static void main(String[] args) {

        final AtomicInteger a=new AtomicInteger();
        Thread mian=new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("操作线程:"+Thread.currentThread().getName()+",初始值:"+a.get());
                int expectNum=a.get();
                int newNum=expectNum+1;
                try {
                    Thread.sleep(1000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                boolean isCASSccuess=a.compareAndSet(expectNum,newNum);
                System.out.println("操作线程:"+Thread.currentThread().getName()+",CAS操作:"+isCASSccuess);
            }
        },"主线程");

        Thread other=new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(100L);
                    a.incrementAndGet();//加1
                    System.out.println("操作线程:"+Thread.currentThread().getName()+",increment:"+a.get());
                    a.decrementAndGet();//减一
                    System.out.println("操作线程:"+Thread.currentThread().getName()+",increment:"+a.get());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"干扰线程");
        mian.start();
        other.start();
    }
}
